package com.yqw.onlineDocs.controller;

import cn.hutool.core.util.ObjectUtil;
import com.yqw.onlineDocs.annotation.DocumentPermissionCheck;
import com.yqw.onlineDocs.common.BaseResponse;
import com.yqw.onlineDocs.common.DeleteRequest;
import com.yqw.onlineDocs.common.ErrorCode;
import com.yqw.onlineDocs.common.ResultUtils;
import com.yqw.onlineDocs.constant.DocumentPermissionConstant;
import com.yqw.onlineDocs.exception.BusinessException;
import com.yqw.onlineDocs.exception.ThrowUtils;
import com.yqw.onlineDocs.model.dto.documentUser.DocumentUserAddRequest;
import com.yqw.onlineDocs.model.dto.documentUser.DocumentUserEditRequest;
import com.yqw.onlineDocs.model.dto.documentUser.DocumentUserQueryRequest;
import com.yqw.onlineDocs.model.entity.DocumentUser;
import com.yqw.onlineDocs.model.entity.User;
import com.yqw.onlineDocs.model.vo.DocumentUserVO;
import com.yqw.onlineDocs.service.DocumentUserService;
import com.yqw.onlineDocs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 文档成员管理
 */
@RestController
@RequestMapping("/documentUser")
@Slf4j
class DocumentUserController {

    @Resource
    private DocumentUserService documentUserService;

    @Resource
    private UserService userService;

    /**
     * 添加成员到文档
     */
    @PostMapping("/add")
    @DocumentPermissionCheck(permission = DocumentPermissionConstant.DOCUMENT_USER_MANAGE, documentIdParam = "documentId")
    public BaseResponse<Long> addDocumentUser(@RequestBody DocumentUserAddRequest documentUserAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(documentUserAddRequest == null, ErrorCode.PARAMS_ERROR);
        long id = documentUserService.addDocumentUser(documentUserAddRequest);
        return ResultUtils.success(id);
    }

    /**
     * 从文档中移除成员
     */
    @PostMapping("/delete")
    @DocumentPermissionCheck(permission = DocumentPermissionConstant.DOCUMENT_USER_MANAGE, documentIdParam = "documentId", fromRequestBody = false)
    public BaseResponse<Boolean> deleteDocumentUser(@RequestBody DeleteRequest deleteRequest,
                                                 HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        DocumentUser oldDocumentUser=documentUserService.getById(id);
        ThrowUtils.throwIf(oldDocumentUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = documentUserService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 查询某个成员在某个文档的信息
     */
    @PostMapping("/get")
    @DocumentPermissionCheck(permission = DocumentPermissionConstant.DOCUMENT_READ, documentIdParam = "documentId")
    public BaseResponse<DocumentUser> getDocumentUser(@RequestBody DocumentUserQueryRequest documentUserQueryRequest) {
        // 参数校验
        ThrowUtils.throwIf(documentUserQueryRequest == null, ErrorCode.PARAMS_ERROR);
        Long documentId = documentUserQueryRequest.getDocumentId();
        Long userId = documentUserQueryRequest.getUserId();
        ThrowUtils.throwIf(ObjectUtil.hasEmpty(documentId, userId), ErrorCode.PARAMS_ERROR);
        // 查询数据库
        DocumentUser documentUser = documentUserService.getOne(documentUserService.getQueryWrapper(documentUserQueryRequest));
        ThrowUtils.throwIf(documentUser == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(documentUser);
    }

    /**
     * 查询成员信息列表
     */
    @PostMapping("/list")
    @DocumentPermissionCheck(permission = DocumentPermissionConstant.DOCUMENT_READ, documentIdParam = "documentId")
    public BaseResponse<List<DocumentUserVO>> listDocumentUser(@RequestBody DocumentUserQueryRequest documentUserQueryRequest,
                                                            HttpServletRequest request) {
        ThrowUtils.throwIf(documentUserQueryRequest == null, ErrorCode.PARAMS_ERROR);
        List<DocumentUser> documentUsers = documentUserService.list(
                documentUserService.getQueryWrapper(documentUserQueryRequest)
        );
        return ResultUtils.success(documentUserService.getDocumentUserVOList(documentUsers));
    }

    /**
     * 编辑成员信息（设置权限）
     */
    @PostMapping("/edit")
    @DocumentPermissionCheck(permission = DocumentPermissionConstant.DOCUMENT_USER_MANAGE, documentIdParam = "id", fromRequestBody = false)
    public BaseResponse<Boolean> editDocumentUser(@RequestBody DocumentUserEditRequest documentUserEditRequest,
                                               HttpServletRequest request) {
        if (documentUserEditRequest == null || documentUserEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        DocumentUser documentUser = new DocumentUser();
        BeanUtils.copyProperties(documentUserEditRequest, documentUser);
        // 数据校验
        documentUserService.validateDocumentUser(documentUser, false);
        // 判断是否存在
        long id = documentUserEditRequest.getId();
        DocumentUser oldDocumentUser = documentUserService.getById(id);
        ThrowUtils.throwIf(oldDocumentUser == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = documentUserService.updateById(documentUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 查询我加入的团队空间列表
     */
    @PostMapping("/list/my")
    public BaseResponse<List<DocumentUserVO>> listMyTeamSpace(HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        DocumentUserQueryRequest documentUserQueryRequest = new DocumentUserQueryRequest();
        documentUserQueryRequest.setUserId(loginUser.getId());
        List<DocumentUser> documentUserList = documentUserService.list(
                documentUserService.getQueryWrapper(documentUserQueryRequest)
        );
        return ResultUtils.success(documentUserService.getDocumentUserVOList(documentUserList));
    }
}
